#include "Texture.h"
#include "SDL_Image.h"

bool Texture::LoadFromFile( const char* name )
{
    SDL_Surface* surf_temp = NULL;

    //if the temp fails, return null
    if((surf_temp = IMG_Load(name)) == NULL)
    {
        return false; 
    }

    //if temp works, load the return surface, and free the temp.
    m_surf = SDL_DisplayFormatAlpha(surf_temp);
    SDL_FreeSurface(surf_temp);

    return true;
}

Color Texture::SampleTexture( float u, float v )
{
    int x = static_cast<int>((float)(m_surf->w-1) * u);
    int y =  static_cast<int>((float)(m_surf->h-1) * v);
    SDL_Color color ;
    color.r = color.g = color.b = 0;
    Uint32 col = 0 ;

    //determine position
    char* pPosition = ( char* ) m_surf->pixels ;

    //offset by y
    pPosition += ( m_surf->pitch * y ) ;

    //offset by x
    pPosition += ( m_surf->format->BytesPerPixel *x ) ;

    //copy pixel data
    memcpy ( &col , pPosition , m_surf->format->BytesPerPixel );

    //convert color
    SDL_GetRGBA ( col , m_surf->format , &color.r , &color.g , &color.b, &color.unused ) ;
    float mul = 1.0f / 255.0f;
    return Color((float)color.r*mul,(float)color.g*mul,(float)color.b*mul);
}

void Texture::CleanUp()
{
    if(m_surf)
        SDL_FreeSurface(m_surf); 
    m_surf = 0;
}
